<?php

/**
 * Description of ECOMAuthenticate
 * This Class Authenticate API USer.
 *  @author Rakesh Srivastava
 */
class ECOMAuthenticate {

    var $authKey;
    var $deviceID;
    var $appKey;

    function __construct() {
        $this->setAuthKey();
        $this->setAppKey();
        $this->setDeviceID();
    }

    public static function getObject() {
        return new ECOMAuthenticate();
    }

    private function setDeviceID() {
        
        $this->deviceID = isset($_SERVER['HTTP_X_DEVICE_ID']) ? $_SERVER['HTTP_X_DEVICE_ID'] : '';
    }

    private function setAuthKey() {
        $this->authKey = isset($_SERVER['HTTP_X_AUTHKEY']) ? $_SERVER['HTTP_X_AUTHKEY'] : '';
    }

    private function setAppKey() {
        $this->appKey = isset($_SERVER['HTTP_X_APPKEY']) ? $_SERVER['HTTP_X_APPKEY'] : '';
    }

    public function getDeviceID() {
        return $this->deviceID;
    }

    public function getAuthKey() {
        return $this->authKey;
    }

    public function isValidAuthKey() {
        if ($this->getAuthKey() == '') {
            return FALSE;
        }
        return TRUE;
    }

    public function isDbAuthKey() {
        $auth = getAuthKeyObj($this->getAuthKey());
        if (!empty($auth->auth_key)) {
            return true;
        } else {
            return false;
        }
    }

    public function getAppKey() {
        return $this->appKey;
    }

    public function isValidAppKey() {
        if ($this->getAppKey() == '') {
            return FALSE;
        }

        $appKeys = explode(',', X_APPKEY);
        if (!in_array($this->getAppKey(), $appKeys)) {
            return FALSE;
        }
        return TRUE;
    }

    public function isValidDeviceID() {
       
        if ($this->getDeviceID() == '') {
            return FALSE;
        }
        return TRUE;
    }

    public function getUserByAuthKey() {

        if ($this->isValidAuthKey()) {
            $auth = self::getAuthKeyObj($this->getAuthKey());
            if ($auth) {
                if ($auth->expires_on >= time()) {
                    return $auth->user_id;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    public function getAuthKeyObj($auth_key) {
        $expires_on = time();
        if (class_exists('AuthKey')) {
            $auth_key_obj = AuthKey::model()->find('auth_key=:auth_key AND expires_on >=:expires_on', array(':auth_key' => $auth_key, ':expires_on' => $expires_on));
        }
        return $auth_key_obj;
    }

}

?>
